
<template>
  <t-card :bordered="false">
    <!-- 容器 -->
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="searchParams.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
        
        <!-- 新建模板 -->
        <t-button
          v-permission="['system:budget-model:create']"
          block
          @click="
            handleOpenLeftDialog('create', {
              companyId: searchParams.companyId,
              fileUrl: []
            })
          "
        >
          新建模板
        </t-button>
        <!-- 模板树 -->
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
          :label="getLabel"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon
                v-permission="['system:budget-model:update']"
                name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })"
              />
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDeleteLeft({ id: node.data.id })"
              >
                <t-icon v-permission="['system:budget-model:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.modelId" class="right">
      <t-form ref="formRef" :data="formDataT" reset-type="initial" >
        <t-form-item label="模板名称" name="name" :rules="[{ required: true, message: '请输入模板名称' }]">
          <t-input v-model:value="formDataT.name" readonly placeholder="请输入模板名称" clearable  />
        </t-form-item>
        <t-form-item label="模板类型" name="type" :rules="[{ required: true, message: '请选择模板类型' }]">
          <t-radio-group v-model:value="formDataT.type" readonly>
            <t-radio
              v-for="_ in typeOption"
              :key="_.value"
              :value="_.value"
              
            >
              {{ _.label }}
            </t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="配置表" v-if="['1'].includes(formDataT.type)" name="fileUrl" :rules="[{ required: true, message: '请选择配置表' }]">
          <preview-excel :file-url="formDataT.fileUrl"/>
        </t-form-item>
        <t-form-item label="注意事项" name="remark" :rules="[{ required: true, message: '请输入注意事项' }]">
          <t-textarea v-model:value="formDataT.remark" placeholder="请输入注意事项" clearable readonly :autosize="true"/>
        </t-form-item>
      </t-form>
      <!-- 中间分类 -->
      <sub-total 
        ref="subTotalRef"
        :model-id="searchParams.modelId" 
        v-if="searchParams.modelId" 
        @type-change="handleTypeChange"
      />
      <!-- sheet -->
      <sheet 
        :model-id="searchParams.modelId" 
        v-if="searchParams.modelId"
        :content-type="searchParams.contentType"
        @refresh-subtotal="handleRefreshSubtotal"
      />
      </div>
      <t-empty v-show="!searchParams.modelId" class="right" title="请先选择模板" style="margin-top: 30vh" />
    </div>

    <!-- 左侧新增对话框 -->
    <custom-dialog
      ref="customDialogLeftRef"
      v-slot="{ formData, readonly }"
      :api-map="budgeModelCRUD"
      header="*模板"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccessLeft"
    >
      <t-form-item label="模板名称" name="name" :rules="[{ required: true, message: '请输入模板名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入模板名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="模板类型" name="type" :rules="[{ required: true, message: '请选择模板类型' }]">
        <t-radio-group v-model:value="formData.type">
          <t-radio
            v-for="_ in typeOption"
            :key="_.value"
            :value="_.value"
            :readonly="readonly"
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
       <t-form-item label="配置表" v-if="['1'].includes(formData.type)" name="fileUrl" :rules="[{ required: true, message: '请输入配置表' }]">
          <upload 
            v-model:files="formData.fileUrl" 
            accept=".xlsx,.xls,.csv"
            :disabled="readonly"
           
            />
      </t-form-item>
      <t-form-item label="注意事项" name="remark" :rules="[{ required: true, message: '请输入注意事项' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入注意事项" clearable :readonly="readonly" />
      </t-form-item>

    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'BudgetModelList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';
import Upload from '@/components/upload/index.vue';
import {  budgeModelCRUD } from '@/api/budget/model';
import { getCompanyList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';
import SubTotal from './components/SubTotal.vue';
import Sheet from './components/Sheet.vue';
import PreviewExcel from './components/PreviewExcel.vue';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 搜索参数
const searchParams = reactive({
  companyId: null,
  modelId: null,
  contentType: 1
});
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    searchParams.companyId = data[0].id;
  });
};
// 前端验证代码（使用FileReader）
// const checkFileType = async (url) => {
//   const response = await fetch(url);
//   const buffer = await response.arrayBuffer();
//   const header = new Uint8Array(buffer).subarray(0, 8);
//   console.log("文件头魔数:", Array.from(header).map(b => b.toString(16)).join(' '));
  
//   // .xls 的魔数：D0 CF 11 E0 A1 B1 1A E1
//   // .xlsx 的魔数：50 4B 03 04
// }
// 模板列表
const categoryList = ref([]);
// 模板树
const categoryTree = ref([]);
// 处理获取模板
const handleGetCategory = () => {
  const params = {
    companyId: searchParams.companyId,
    pageSize: -1,
  };
  budgeModelCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};
const formDataT = ref<Record<string, any>>({});
onMounted(async () => {
  await handleGetCompanySimpleList();
  handleGetCategory();
});
// 处理点击模板树
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (!node.data.children) {
    searchParams.modelId = node.value;
    budgeModelCRUD.get({id:searchParams.modelId}).then((data) => {
    formDataT.value = data;
  });
  }
};
// 自定义材料左侧对话框ref
const customDialogLeftRef = useTemplateRef('customDialogLeftRef');
// 处理打开对话框
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogLeftRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccessLeft = (result: Record<string, any>) => {
  handleGetCategory();
  if(searchParams.modelId) {
    budgeModelCRUD.get({id:searchParams.modelId}).then((data) => {
    formDataT.value = data;
  });
  }
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  if(params.type=== '1') {
    if(!params.fileUrl) {
      params.fileUrl = []
    }
 
  }
};
// 处理删除左侧
const handleDeleteLeft = (params: Record<string, any>) => {
  if(params.children) {
    MessagePlugin.error('有子节点不允许删除');
  } else {
    budgeModelCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功'); 
      handleGetCategory();
      searchParams.modelId = null;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
  }
 
};
// 处理分类汇总改变
const handleTypeChange = (contentType: any) => {
  searchParams.contentType = contentType
  console.log(contentType,'2211');
  
}
// 处理公司id改变
const handleChangeCompany = () => {
  searchParams.modelId = null;
  handleGetCategory();
}
const typeOption = [{label:'套餐报价', value:'1'},{label:'清单报价', value:'2'}]
const getLabel = (h: any, node: { data: any; }) => {
  const { data } = node;
  return `${data.name}(${typeOption.find((item) => item.value === data.type)?.label})`
};
// 中间部分的ref
const subTotalRef = useTemplateRef('subTotalRef');

const handleRefreshSubtotal = () => {
  subTotalRef.value.refreshTable();
  console.log(11);
  
};
</script>

<style lang="less" scoped>
// 容器
.container {
  // display: flex;
  // justify-content: center;
  // align-items: flex-start;
  display: flex;
  height: calc(100vh - 236px); // 设置容器高度

  .left {
    width: 300px;
    flex-shrink: 0; // 防止左侧被压缩
    height: calc(100vh - 236px);
    overflow: hidden;
    position: sticky; // 使用sticky定位
    top: 0; // 距离顶部0
    height: 100%; // 高度与容器一致
    overflow-y: auto; // 如果内容超出高度，左侧也可以滚动

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    // height: calc(100vh - 236px);
    height: 100%;
    flex-shrink: 0; // 防止分隔线被压缩
  }

  .right {
    // width: calc(100% - 325px);
    flex-grow: 1; // 右侧占据剩余空间
    overflow-y: auto; // 允许右侧滚动
    padding-left: 16px; // 添加一些左边距
  }
}
</style>
